<?php
namespace App\Tools\TencentYoutuyun;

use App\Tools\TencentYoutuyun\Http;
class TencentYoutu {
  // 30 days
  const EXPIRED_SECONDS = 2592000;
  const HTTP_BAD_REQUEST = 400;
  const HTTP_SERVER_ERROR = 500;

  /**
   * return the status message
   */
  public static function statusText($status)
  {
    switch ($status) {
      case 0:
        $statusText = 'CONNECT_FAIL';
        break;
      case 200:
        $statusText = 'HTTP OK';
        break;
      case 400:
        $statusText = 'BAD_REQUEST';
        break;
      case 401:
        $statusText = 'UNAUTHORIZED';
        break;
      case 403:
        $statusText = 'FORBIDDEN';
        break;
      case 404:
        $statusText = 'NOTFOUND';
        break;
      case 411:
        $statusText = 'REQ_NOLENGTH';
        break;
      case 423:
        $statusText = 'SERVER_NOTFOUND';
        break;
      case 424:
        $statusText = 'METHOD_NOTFOUND';
        break;
      case 425:
        $statusText = 'REQUEST_OVERFLOW';
        break;
      case 500:
        $statusText = 'INTERNAL_SERVER_ERROR';
        break;
      case 503:
        $statusText = 'SERVICE_UNAVAILABLE';
        break;
      case 504:
        $statusText = 'GATEWAY_TIME_OUT';
        break;
      default:
        $statusText = $status;
        break;
    }
    return $statusText;
  }

  /**
   * return the status message
   */
  public static function getStatusText()
  {
    $info = Http::info();
//    $status = $info['http_code'];
    $status = 200;
    return self::statusText($status);
  }

  /**
   * @param $url 待检测的图片url
   * @return 返回的结果，JSON字符串，字段参见API文档
   */
  public static function generalocrurl($url, $seq = '')
  {

    $expired = time() + self::EXPIRED_SECONDS;
    $postUrl = Conf::$END_POINT . 'youtu/ocrapi/generalocr';
    $sign = Auth::appSign($expired, Conf::$USER_ID);

    $post_data = array(
      'app_id' => Conf::$APPID,
      'url' => $url
    );

    $req = array(
      'url' => $postUrl,
      'method' => 'post',
      'timeout' => 10,
      'data' => json_encode($post_data),
      'header' => array(
        'Authorization:' . $sign,
        'Content-Type:text/json',
        'Expect: ',
      ),
    );

    $rsp = Http::send($req);
    $ret = json_decode($rsp, true);

    if (!$ret) {
      return self::getStatusText();
    }
    return $ret;
  }
}
